package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.*;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UpdateOrderServlet extends HttpServlet {
    private static final String CART_FORM="/WEB-INF/jsp/order/newOrder.jsp";

    public static int count=1;

    private String orderMsg="";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();//先前一直用session，取不到值why？？
        String address=req.getParameter("addressset");
        System.out.println("--------"+address);

        //System.out.println(address);

        Cart cart = (Cart) session.getAttribute("cart");
        if(cart==null){
            cart = new Cart();
        }
        Iterator<CartItem> cartItemss= cart.getAllCartItems();
        List<CartItem> cartItems = cart.getCartItemList();

        while (cartItemss.hasNext()) {
            CartItem cartItem = (CartItem) cartItemss.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                String quantityString = req.getParameter(itemId);
                int quantity =Integer.parseInt(quantityString);

                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItemss.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }

        AccountDao accountDao = new AccountDaoImpl();
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        if (loginAccount != null) {

            if(accountDao.selectShoppingcartByUsernameAndTimes(loginAccount) && count == 1){
                //数据库中有购物信息，且次数为1，便提取信息
                List<CartItem> cartItems2= new ArrayList<>();
                List<Item> itemList= new ArrayList<>();
                List<Product> productList= new ArrayList<>();

                accountDao.selectShoppingcart(loginAccount,cartItems2,itemList,productList);
                //提取数据库信息

                for(int i=0;i<itemList.size();i++){
                    cart.addItem(itemList.get(i),cartItems2.get(i).isInStock());
                    cart.setQuantityByItemId(itemList.get(i).getItemId(),cartItems2.get(i).getQuantity());
                }

                session.setAttribute("cart",cart);
                session.setAttribute("cartItems",cartItems2);
                count++;
                req.getRequestDispatcher(CART_FORM).forward(req, resp);
            }
            else {

                accountDao.deleteShoppingcartByUsername(loginAccount);
                //待解决,如何更新数量为0的数据
                for(int i=0;i<cartItems.size();i++){
                    CartItem cartItem = cartItems.get(i);
                    if(accountDao.selectShoppingcartByUsernameAndItemId(loginAccount,cartItem)){
                        //如果表中已有数据，更新数量
                        accountDao.updateShoppingcartByUsernameAndItemid(loginAccount,cartItem);
                    }
                    else {
                        //如果表中没有数据，则插入
                        Item item = cartItem.getItem();
                        Product product= item.getProduct();
                        accountDao.insertShoppingcart(loginAccount,cartItem,item,product,address);
                    }
                }
            }
        }

        cart = null;
        if(cart==null && !accountDao.selectShoppingcartByUsernameAndTimes(loginAccount)){
            this.orderMsg="Successfully Paied";
            session.setAttribute("orderMsg",this.orderMsg);
            session.setAttribute("cart",cart);
        }
        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}
